<?php

namespace App\Models\OpenShop\Organization;

use App\Models\BaseModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationRegionMappingModel;
use App\Models\Traits\KfSoftDeletes;
use App\Models\Traits\KfUid;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Facades\Cache;

class OpenShopRegionManageModel extends BaseModel
{
    use HasFactory, KfSoftDeletes, KfUid;

    protected $table = "open_shop_region_manage";

    /**
     * @return HasMany
     */
    public function regionMappingRel(): HasMany
    {
        return $this->hasMany(OpenShopRegionManageMappingModel::class, "regionId", "id");
    }

    /**
     * @return HasMany
     */
    public function regionUserMappingRel(): HasMany
    {
        return $this->hasMany(OpenShopRegionManageUserMappingModel::class, "regionId", "id");
    }


    /**
     * 通过省区code获得战区信息
     * @param int $provinceCode
     * @return array
     */
    public static function getWarZoneInfoByProvinceCode(int $provinceCode, string $cacheStore = 'redis'): array
    {
        return Cache::store($cacheStore)->remember('war_zone_info_by_province_code_v2:' . $provinceCode, 5 * 60, function () use ($provinceCode) {
            // 通过省区code获得manageId
            $manageId = (int)OpenShopOrganizationRegionMappingModel::query()
                ->where('provinceCode', $provinceCode)
                ->value('manageId');

            if (!$manageId) {
                return [];
            }

            $regionId = (int)OpenShopRegionManageMappingModel::query()
                ->where('manageId', $manageId)
                ->value('regionId');

            if (!$regionId) {
                return [];
            }

            $openShopRegionManageModel = OpenShopRegionManageModel::query()
                ->where('id', $regionId)
                ->with(['regionUserMappingRel'])
                ->first();

            if ($openShopRegionManageModel == null) {
                return [];
            }

            $userInfo = collect($openShopRegionManageModel->regionUserMappingRel)->where('type', OpenShopRegionManageUserMappingModel::USER_TYPE_1)->first();

            if ($userInfo == null) {
                return [];
            }

            return [
                'regionId' => $regionId,
                'regionName' => $openShopRegionManageModel->name,
                'manageId' => $manageId,
                'username' => $userInfo->username,
                'userId'   => $userInfo->userId,
            ];
        });
    }
}
